// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 速度显示元素
const speedElement = document.getElementById('speed');
// 当前速度
let speed = 0;
// 最大速度
const MAX_SPEED = 10;
// 加速度
const ACCELERATION = 0.1;
// 减速度
const DECELERATION = 0.05;

// 过山车轨道点
const trackPoints = [
    { x: 50, y: 500 },
    { x: 200, y: 100 },
    { x: 400, y: 500 },
    { x: 600, y: 100 },
    { x: 750, y: 500 }
];

// 当前轨道点索引
let currentPointIndex = 0;
// 轨道点之间的进度
let trackProgress = 0;

// 绘制轨道
function drawTrack() {
    ctx.beginPath();
    ctx.moveTo(trackPoints[0].x, trackPoints[0].y);
    for (let i = 1; i < trackPoints.length; i++) {
        ctx.lineTo(trackPoints[i].x, trackPoints[i].y);
    }
    ctx.strokeStyle = 'brown';
    ctx.lineWidth = 5;
    ctx.stroke();
}

// 绘制过山车
function drawRollerCoaster() {
    const currentPoint = trackPoints[currentPointIndex];
    const nextPoint = trackPoints[(currentPointIndex + 1) % trackPoints.length];
    const dx = nextPoint.x - currentPoint.x;
    const dy = nextPoint.y - currentPoint.y;
    const x = currentPoint.x + dx * trackProgress;
    const y = currentPoint.y + dy * trackProgress;

    ctx.beginPath();
    ctx.arc(x, y, 20, 0, Math.PI * 2);
    ctx.fillStyle = 'red';
    ctx.fill();
    ctx.closePath();
}

// 移动过山车
function moveRollerCoaster() {
    trackProgress += speed;
    if (trackProgress >= 1) {
        trackProgress = 0;
        currentPointIndex = (currentPointIndex + 1) % trackPoints.length;
    }
}

// 处理键盘事件控制速度
document.addEventListener('keydown', function (event) {
    if (event.key === 'ArrowUp' && speed < MAX_SPEED) {
        speed += ACCELERATION;
    } else if (event.key === 'ArrowDown' && speed > 0) {
        speed -= DECELERATION;
    }
    speedElement.textContent = speed.toFixed(2);
});

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawTrack();
    drawRollerCoaster();
    moveRollerCoaster();

    requestAnimationFrame(gameLoop);
}

// 初始化游戏
gameLoop();